/**
 * 应用程序主入口
 * 启动WebSocket服务器和HTTP服务器
 */

const Logger = require('./utils/logger');
const config = require('./utils/config');
const WebSocketServer = require('./server/WebSocketServer');
const HTTPServer = require('./server/HTTPServer');

class Application {
  constructor() {
    this.logger = new Logger('Application');
    this.webSocketServer = null;
    this.httpServer = null;
    this.isRunning = false;
    
    // 绑定进程事件
    this.bindProcessEvents();
  }

  /**
   * 启动应用程序
   */
  async start() {
    if (this.isRunning) {
      this.logger.warn('应用程序已在运行');
      return;
    }

    try {
      this.logger.info('正在启动应用程序...');
      
      // 验证配置
      config.validate();
      this.logger.info('配置验证通过');
      
      // 启动WebSocket服务器
      this.webSocketServer = new WebSocketServer();
      await this.webSocketServer.start();
      
      // 启动HTTP服务器
      this.httpServer = new HTTPServer(this.webSocketServer);
      await this.httpServer.start();
      
      this.isRunning = true;
      
      // 输出启动信息
      const wsAddress = this.webSocketServer.getAddress();
      const httpInfo = this.httpServer.getServerInfo();
      
      this.logger.success('应用程序启动成功！');
      console.log('\n' + '='.repeat(60));
      console.log('🚀 小智 WebSocket 示例程序已启动');
      console.log('='.repeat(60));
      console.log(`📡 WebSocket 服务器: ws://${wsAddress.host}:${wsAddress.port}`);
      console.log(`🌐 HTTP 服务器: http://${httpInfo.host}:${httpInfo.port}`);
      console.log(`📱 客户端访问: http://${httpInfo.host}:${httpInfo.port}`);
      console.log(`🔧 环境模式: ${config.get('environment')}`);
      console.log('='.repeat(60));
      console.log('💡 提示: 在浏览器中访问 HTTP 地址开始使用聊天室');
      console.log('🛑 停止服务: 按 Ctrl+C\n');
      
    } catch (error) {
      this.logger.error('应用程序启动失败', { 
        error: error.message,
        stack: error.stack 
      });
      await this.stop();
      process.exit(1);
    }
  }

  /**
   * 停止应用程序
   */
  async stop() {
    if (!this.isRunning) {
      this.logger.warn('应用程序未在运行');
      return;
    }

    try {
      this.logger.info('正在停止应用程序...');
      
      // 停止HTTP服务器
      if (this.httpServer) {
        await this.httpServer.stop();
        this.httpServer = null;
      }
      
      // 停止WebSocket服务器
      if (this.webSocketServer) {
        await this.webSocketServer.stop();
        this.webSocketServer = null;
      }
      
      this.isRunning = false;
      
      this.logger.success('应用程序已停止');
      
    } catch (error) {
      this.logger.error('停止应用程序失败', { 
        error: error.message 
      });
      throw error;
    }
  }

  /**
   * 绑定进程事件
   */
  bindProcessEvents() {
    // 优雅关闭处理
    const gracefulShutdown = async (signal) => {
      this.logger.info(`收到 ${signal} 信号，开始优雅关闭...`);
      
      try {
        await this.stop();
        this.logger.info('优雅关闭完成');
        process.exit(0);
      } catch (error) {
        this.logger.error('优雅关闭失败', { error: error.message });
        process.exit(1);
      }
    };

    // 监听终止信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));

    // 监听未处理的异常
    process.on('uncaughtException', (error) => {
      this.logger.error('未捕获的异常', { 
        error: error.message,
        stack: error.stack 
      });
      process.exit(1);
    });

    // 监听未处理的Promise拒绝
    process.on('unhandledRejection', (reason, promise) => {
      this.logger.error('未处理的Promise拒绝', { 
        reason: reason?.message || reason,
        stack: reason?.stack 
      });
      process.exit(1);
    });

    // 内存警告
    process.on('warning', (warning) => {
      this.logger.warn('进程警告', { 
        name: warning.name,
        message: warning.message 
      });
    });
  }

  /**
   * 获取应用程序状态
   */
  getStatus() {
    return {
      isRunning: this.isRunning,
      webSocketServer: this.webSocketServer ? {
        running: this.webSocketServer.isServerRunning(),
        address: this.webSocketServer.getAddress(),
        stats: this.webSocketServer.getStats()
      } : null,
      httpServer: this.httpServer ? {
        info: this.httpServer.getServerInfo()
      } : null,
      process: {
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        pid: process.pid,
        version: process.version,
        platform: process.platform
      },
      config: {
        environment: config.get('environment'),
        nodeEnv: process.env.NODE_ENV
      }
    };
  }

  /**
   * 重启应用程序
   */
  async restart() {
    this.logger.info('正在重启应用程序...');
    
    await this.stop();
    await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒
    await this.start();
    
    this.logger.info('应用程序重启完成');
  }
}

// 如果是直接运行此文件，则启动应用程序
if (require.main === module) {
  const app = new Application();
  
  // 启动应用程序
  app.start().catch((error) => {
    console.error('启动失败:', error.message);
    process.exit(1);
  });
}

module.exports = Application;